package mgodb

import (
	"jgt-oper/src/model"
	"jgt-oper/src/schema"
	"jgt-oper/src/service/mongo"
	"time"

	"github.com/facebookgo/inject"
	"github.com/globalsign/mgo"
	"github.com/globalsign/mgo/bson"
	"github.com/pkg/errors"
)

// cAppVersion 应用版本管理表名
const cAppVersion = "oper_app_version"

// AppVersion 应用版本管理
type AppVersion struct {
	DB *mongo.DB
}

// Init 初始化
func (a *AppVersion) Init(g *inject.Graph, db *mongo.DB) {
	a.DB = db

	// 初始化mongo索引
	a.DB.C(cAppVersion, func(c *mgo.Collection) error {
		c.EnsureIndex(mgo.Index{
			Key:    []string{"record_id"},
			Unique: true,
		})
		c.EnsureIndexKey("device_type")
		c.EnsureIndexKey("version")
		c.EnsureIndexKey("status")
		c.EnsureIndexKey("upgrade")
		c.EnsureIndexKey("deleted")
		return nil
	})

	var val model.IAppVersion = a
	g.Provide(&inject.Object{Value: val, Name: "IAppVersion"})
}

// QueryPage 查询分页数据
func (a *AppVersion) QueryPage(params schema.AppVersionQueryParam, pageIndex, pageSize uint) (int64, []*schema.AppVersionQueryResult, error) {
	query := bson.M{
		"deleted": 0,
	}

	if v := params.Status; v > 0 {
		query["status"] = v
	}
	if v := params.Upgrade; v > 0 {
		query["upgrade"] = v
	}
	if v := params.DeviceType; v != "" {
		query["device_type"] = v
	}
	if v := params.Name; v != "" {
		query["name"] = bson.M{"$regex": v}
	}
	if v := params.Title; v != "" {
		query["title"] = bson.M{"$regex": v}
	}

	var total int64
	var items []*schema.AppVersionQueryResult
	err := a.DB.C(cAppVersion, func(c *mgo.Collection) error {
		n, err := c.Find(query).Count()
		if err != nil {
			return err
		}
		total = int64(n)
		if total == 0 {
			return nil
		}

		return c.Find(query).Sort("-_id").Skip(int((pageIndex - 1) * pageSize)).Limit(int(pageSize)).All(&items)
	})
	if err != nil {
		return 0, nil, errors.Wrapf(err, "查询分页数据发生错误")
	}

	return total, items, nil
}

// CheckDeviceTypeAndVersion 检查设备类型和版本是否存在
func (a *AppVersion) CheckDeviceTypeAndVersion(deviceType string, version int64) (bool, error) {
	var exists bool
	err := a.DB.C(cAppVersion, func(c *mgo.Collection) error {
		n, err := c.Find(bson.M{"device_type": deviceType, "version": version, "deleted": 0}).Count()
		if err != nil {
			return err
		}
		exists = n > 0
		return nil
	})
	if err != nil {
		return false, errors.Wrapf(err, "检查设备类型和版本是否存在发生错误")
	}
	return exists, nil
}

// Get 精确查询数据
func (a *AppVersion) Get(recordID string) (*schema.AppVersion, error) {
	var item schema.AppVersion
	err := a.DB.C(cAppVersion, func(c *mgo.Collection) error {
		return c.Find(bson.M{"record_id": recordID, "deleted": 0}).One(&item)
	})
	if err != nil {
		if err == mgo.ErrNotFound {
			return nil, nil
		}
		return nil, errors.Wrapf(err, "精确查询数据发生错误")
	}
	return &item, nil
}

// Create 创建数据
func (a *AppVersion) Create(item *schema.AppVersion) error {
	err := a.DB.C(cAppVersion, func(c *mgo.Collection) error {
		id, err := a.DB.IncrID(cAppVersion)
		if err != nil {
			return err
		}
		item.ID = id
		return c.Insert(item)
	})
	if err != nil {
		return errors.Wrapf(err, "创建数据发生错误")
	}

	return nil
}

// Update 更新数据
func (a *AppVersion) Update(recordID string, info map[string]interface{}) error {
	err := a.DB.C(cAppVersion, func(c *mgo.Collection) error {
		return c.Update(bson.M{"record_id": recordID}, bson.M{"$set": info})
	})
	if err != nil {
		return errors.Wrapf(err, "更新数据发生错误")
	}
	return nil
}

// Delete 删除数据
func (a *AppVersion) Delete(recordID string) error {
	info := map[string]interface{}{
		"deleted": time.Now().Unix(),
	}
	err := a.DB.C(cAppVersion, func(c *mgo.Collection) error {
		return c.Update(bson.M{"record_id": recordID}, bson.M{"$set": info})
	})
	if err != nil {
		return errors.Wrapf(err, "删除数据发生错误")
	}
	return nil
}

// GetUpgradeVersion 检查升级版本
func (a *AppVersion) GetUpgradeVersion(deviceType string, version int64) (*schema.AppVersion, error) {
	query := bson.M{
		"deleted":     0,
		"status":      1,
		"device_type": deviceType,
		"version":     bson.M{"$gt": version},
	}

	var item schema.AppVersion
	err := a.DB.C(cAppVersion, func(c *mgo.Collection) error {
		return c.Find(query).Sort("-upgrade", "-version").Limit(1).One(&item)
	})
	if err != nil {
		if err == mgo.ErrNotFound {
			return nil, nil
		}
		return nil, errors.Wrap(err, "检查升级版本发生错误")
	}

	return &item, nil
}
